//
//  TopSliderView.swift
//  RuiQue-Swift
//
//  Created by xiute on 2018/10/31.
//  Copyright © 2018 cuijin. All rights reserved.
//

import UIKit
import RQConfig

typealias SelectIndex = (_ index: Int) -> Void

class TopSliderView: UIView {
    
    private var _datasource: Array<String>?
    var selectBlock: SelectIndex?
    
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(self.lineView)
    }
    
    
    public func didSelect(index: Int) {
        let width = kScreenWidth / CGFloat((self.datasource?.count)!)
        UIView.animate(withDuration: 0.25) {
            self.lineView.frame = CGRect.init(x: width * CGFloat(index), y: 44 - 2, width: width, height: 2)
        }
    }
    
    
    var datasource: Array<String>? {
        get {
            return _datasource
        }
        
        set {
            _datasource = newValue
            self.handleViews()
        }
    }
    
    @objc private func selectIndex(_ sender: UIButton) {
        if self.selectBlock != nil {
            self.selectBlock!(sender.tag - 1000)
        }
        self.didSelect(index: sender.tag - 1000)
    }
    
    
    private func handleViews() -> Void {
        let width = kScreenWidth / CGFloat((self.datasource?.count)!)
        var x:CGFloat = 0
        if !self.lineView.frame.origin.x.isNaN {
            x = self.lineView.frame.origin.x
        }
        
        self.lineView.frame = CGRect.init(x: x, y: 44 - 2, width: kScreenWidth / CGFloat((self.datasource?.count)!), height: 2)
        for obj in self.subviews {
            if obj.tag >= 1000 {
                obj.removeFromSuperview()
            }
        }
        //这里可以使用collectionview 时间问题 直接加上了
        for i in 0..<(self.datasource?.count)! {
            let button = UIButton(frame: CGRect.init(x: CGFloat(i) * width, y: 0, width: width, height: 44))
            button.setTitle(self.datasource![i], for: UIControl.State.normal)
            button.tag = 1000 + i
            button.addTarget(self, action: #selector(selectIndex(_:)), for: UIControl.Event.touchUpInside)
            button.setTitleColor(UIColor.red, for: UIControl.State.normal)
            self.addSubview(button)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var lineView: UIView = {
        var view = UIView(frame: CGRect.init(x: 0, y: 44 - 2, width: 0, height: 2))
        view.backgroundColor = UIColor.orange
        return view
    }()
    
    
    
}
